//
//  PersonViewController.m
//  liangyi
//
//  Created by 张水 on 16/12/20.
//  Copyright © 2016年 yswh. All rights reserved.
//

#import "PersonViewController.h"
#import "UserModel.h"
#import "ChangPhoneViewController.h"
#import "areaModel.h"
@interface PersonViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIPickerViewDelegate,UIPickerViewDataSource>{
    UIAlertView *alertView;
}

@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NSArray *array;

@property(nonatomic,strong) NSMutableArray *areaArrData;

@property(nonatomic,copy)NSString *userName;

@property(nonatomic,copy)NSString *userSex;

@property(nonatomic,copy)NSString *userPhone;

@property(nonatomic,copy)NSString *userAge;

@property(nonatomic,copy)NSString *userArea;

@property(nonatomic,strong) UIImageView *imgView;

@property(nonatomic,strong) UserModel *model;

@property(nonatomic,strong) UIActionSheet *sheet;

@property(nonatomic,strong) UIActionSheet *sheet1;

@property(nonatomic,strong) UIPickerView *areaPickView;

@property(nonatomic,strong) UIImagePickerController *imagePickerController;

@end

@implementation PersonViewController

static NSString *PersonID = @"PersonID";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人资料";
    self.areaArrData = [NSMutableArray array];
    self.userAge = 0;
    self.userSex = @"保密";
    self.userArea = @"保密";
    self.array = [NSArray arrayWithObjects:@"用户名",@"手机号码",@"性别",@"年龄",@"地区",  nil];
    [self initUI];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getUserInfo];
    [self getProvinceData];
}

-(void)initUI{
    
    self.areaPickView = [[UIPickerView alloc]init];
    self.areaPickView.delegate = self;
    self.areaPickView.dataSource = self;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor ColorWithHex:@"#ecf1f2"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveUserInfo)];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return  2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PersonID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:PersonID];
    }
    
    cell.textLabel.textColor = [UIColor ColorWithHex:@"#686868"];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if  (indexPath.section == 0 ){
        self.imgView = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth - 100, 13,50,50)];
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",BaseIamgeUrl,self.model.userHead]] placeholderImage:[UIImage imageNamed:@"user"]];
        self.imgView.clipsToBounds = YES;
        cell.textLabel.text = @"头像";
        self.imgView.contentMode = UIViewContentModeScaleAspectFill;
        self.imgView.layer.cornerRadius = 25;
        [cell addSubview:self.imgView];
    }else{
        cell.textLabel.text = self.array[indexPath.row];
        if (indexPath.row == 0){
            cell.detailTextLabel.text = self.model.userName;
            self.userName = self.model.userName;
        }
        if (indexPath.row == 1) {
            cell.detailTextLabel.text = self.model.userPhone;
            self.userPhone = self.model.userPhone;
        }
        if (indexPath.row == 2) {
            if (self.model.userSex == nil){
                cell.detailTextLabel.text = self.userSex;
            }else{
                cell.detailTextLabel.text = self.model.userSex;
                self.userSex = self.model.userSex;
            }
        }
        if (indexPath.row == 3 ){
            if (self.model.userAge == nil){
                cell.detailTextLabel.text = self.userAge;
            }else{
                cell.detailTextLabel.text = self.model.userAge;
                self.userAge  = self.model.userAge;
            }
        }
        if (indexPath.row == 4 ){
            if (self.model.userAddress == nil){
                cell.detailTextLabel.text = self.userArea;
            }else{
            cell.detailTextLabel.text = self.model.userAddress;
            self.userArea = self.model.userAddress;
            }
        }
    }
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
    if (indexPath.section == 0 ) {
        
        self.sheet = [[UIActionSheet alloc]initWithTitle:@"修改头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选取",@"相机", nil];
        [self.sheet showInView:self.view];
        
    }else{
        
        if (indexPath.row == 0){
            
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"修改用户名" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
        }];
        UIAlertAction *done = [UIAlertAction actionWithTitle:@"修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             UITableViewCell *cell =  [self.tableView cellForRowAtIndexPath:indexPath];
            cell.detailTextLabel.text = [alertVC.textFields lastObject].text;
            self.userName = [alertVC.textFields lastObject].text;
            NSLog(@"%@",self.userName);
        }];
        [alertVC addAction:cancle];
        [alertVC addAction:done];
        [self presentViewController:alertVC animated:YES completion:nil];
            
        }
        
        if (indexPath.row == 1){
            
            [self.navigationController pushViewController:[ChangPhoneViewController  new] animated:YES];
        }
        
        if (indexPath.row == 2){
            self.sheet1 = [[UIActionSheet  alloc]initWithTitle:@"请选择性别" delegate:self cancelButtonTitle:@"取消"destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
            [self.sheet1 showInView:self.view];
        }
        
        if (indexPath.row == 3){
         
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"您的年龄" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                
            }];
            UIAlertAction *done = [UIAlertAction actionWithTitle:@"修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                UITableViewCell *cell =  [self.tableView cellForRowAtIndexPath:indexPath];
                cell.detailTextLabel.text = [alertVC.textFields lastObject].text;
                self.userAge = [alertVC.textFields lastObject].text;
                NSLog(@"%@",self.userAge);
            }];
            [alertVC addAction:cancle];
            [alertVC addAction:done];
            [self presentViewController:alertVC animated:YES completion:nil];
            
        }
        }
        
        if (indexPath.row == 4){
         
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"您所在的地区\n\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertVC.view addSubview:self.areaPickView];
            [self.areaPickView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(alertVC.mas_bottomLayoutGuideTop).offset(-225);
                make.width.equalTo(alertVC.view.mas_width);
            }];
            UIAlertAction *done = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                UITableViewCell *cell =  [self.tableView cellForRowAtIndexPath:indexPath];
                cell.detailTextLabel.text = self.userArea;
                [cell.detailTextLabel setNeedsDisplay];
                NSLog(@"%@",self.userArea);
            }];
            [alertVC addAction:cancle];
            [alertVC addAction:done];
            [self presentViewController:alertVC animated:YES completion:nil];
            
        }
    
}
    


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor ColorWithHex:@"#ecf1f2"];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return  0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor ColorWithHex:@"#ecf1f2"];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return  10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 ){
        return 75;
    }else{
        return 45;
    }
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.areaArrData.count;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    areaModel  *model = self.areaArrData[row];
    return model.name;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    areaModel  *model = self.areaArrData[row];
    self.userArea = model.name;
    NSLog(@"%@",self.userArea);
}



#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:1];
    UITableViewCell *cell =  [self.tableView cellForRowAtIndexPath:indexPath];
    
    if (self.sheet == actionSheet){
            if (buttonIndex == 0) {
                self.imagePickerController = [[UIImagePickerController alloc]init];
                self.imagePickerController.delegate = self;
                self.imagePickerController.allowsEditing = YES;
                self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:self.imagePickerController animated:YES completion:nil];
                
            }
            
            if (buttonIndex == 1) {
                self.imagePickerController = [[UIImagePickerController alloc]init];
                self.imagePickerController.delegate = self;
                self.imagePickerController.allowsEditing = YES;
                UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
                if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                }
                self.imagePickerController.sourceType = sourceType;
                [self presentViewController:self.imagePickerController animated:YES completion:nil];
            }
    }else{
        
        if (buttonIndex == 0){
            cell.detailTextLabel.text = @"男";
            self.userSex = @"男";
            [cell.detailTextLabel setNeedsDisplay];
        }
        if (buttonIndex == 1){
            cell.detailTextLabel.text = @"女";
            self.userSex = @"女";
            [cell.detailTextLabel setNeedsDisplay];
        }
        
    }
    
}

#pragma mark - image picker control delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        self.imgView.image = [info objectForKey:UIImagePickerControllerEditedImage];
        [self changeIcon];
    }];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)saveUserInfo{
    NSString *url = [BASEURL stringByAppendingString:kURL_UpDate];
    
    NSDictionary *dict = @{@"userName":self.userName,
                           @"userSex":self.userSex,
                           @"userAge":self.userAge,
                           @"userAddress":self.userArea};
    NSLog(@"%@",dict);
    NSString *jsonString = [NSString dictionaryToJson:dict];
    NSString *AESString = [NSString AES128Encrypt:jsonString];
    NSDictionary *parameters = @{@"parameters":AESString,
                                 @"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0) {
            [CustomProgressHUD showSuccessWithStatus:@"保存成功"];
        }else {
            [CustomProgressHUD showErrorWithStatus:network.errorDescription];
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error ];
    }];
}


-(void)changeIcon{
    
    CGSize size = CGSizeMake(self.imgView.image.size.width * 0.2, self.imgView.image.size.height *0.2);
    UIImage *image = [CommonMethod imageWithImage:self.imgView.image scaledToSize:size];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSString *imgData = [NSData encodeBase64Data:imageData];
    NSString *url = [BASEURL stringByAppendingString:kURl_ChangHead];
    NSDictionary *dict = @{@"photo":imgData};
    NSString *jsonString = [NSString dictionaryToJson:dict];
    NSString *AESString = [NSString AES128Encrypt:jsonString];
    NSDictionary *parameters = @{@"parameters":AESString,
                                 @"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            [CustomProgressHUD showSuccessWithStatus:@"修改头像成功!!!"];
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];
    
}


-(void)getUserInfo{
    
    NSString *url = [BASEURL stringByAppendingString:kURL_GetUserInfo];
    NSDictionary *dict = @{@"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    [AppNetwork requestWithPath:url parameters:dict success:^(id responseObject) {
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            self.model = [UserModel mj_objectWithKeyValues:network.dataObject];
            [self.tableView reloadData];
        }else{
            [CustomProgressHUD showErrorWithStatus:network.errorDescription];
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];
}
-(void)getProvinceData{
    [AppNetwork requestWithPath:@"http://api.myausplus.com/area/getProvice" parameters:nil success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            if ([network.dataObject isKindOfClass:[NSArray class]]){
                [self.areaArrData removeAllObjects];
                NSArray *arr = [areaModel mj_objectArrayWithKeyValuesArray:network.dataObject];
                [self.areaArrData addObjectsFromArray:arr];
                NSLog(@"%lud",(unsigned long)self.areaArrData.count);
            }else{
//                [CustomProgressHUD showErrorWithStatus:network.errorDescription];
            }
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];
}





@end
